Block chain intelligent contract abnormal transaction information detection method and system

By constructing a multidimensional feature engineering and autoencoder semi-supervised model, and combining various optimization strategies, the problems of high false alarm rate and insufficient sensitivity to new attacks in the detection of abnormal transactions in blockchain smart contracts are solved, and efficient and accurate abnormal transaction detection and risk assessment are achieved.

CN121903604APending Publication Date: 2026-04-21NARI NANJING CONTROL SYSTEM CO LTD +1
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
NARI NANJING CONTROL SYSTEM CO LTD
Filing Date
2025-12-09
Publication Date
2026-04-21

Smart Images

  • Figure CN121903604A_ABST
    Figure CN121903604A_ABST
Patent Text Reader

Abstract

The invention provides a block chain smart contract abnormal transaction information detection method and system, and aims to solve the problems of dependence on a large amount of manual annotation data, insufficient model generalization ability and high false alarm rate of a traditional method. The method mainly comprises the following steps: data acquisition and preprocessing, feature engineering, integrated model construction and training, two-stage training, and semi-supervised optimization and calibration. The system realizes real-time or quasi-real-time detection of abnormal transactions through model reasoning, abnormal scoring, dynamic risk assessment and early warning. The method is expected to be capable of remarkably improving the detection rate of unknown attacks, reducing false alarms and reducing manual annotation dependence.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention belongs to the field of blockchain security technology, specifically relating to a method and system for detecting abnormal transaction information in blockchain smart contracts. Background Technology

[0002] Smart contracts, as computer programs that automatically execute predefined business logic and protocol terms on the blockchain, are the core engine for realizing the enormous potential of blockchain technology, greatly expanding the functional boundaries and application scenarios of blockchain. However, the widespread application of smart contracts is also accompanied by increasingly severe security challenges. Because smart contract code is usually difficult to modify once deployed on the blockchain, potential programming defects, logical vulnerabilities, and malicious behavior from external accounts interacting with it can all be exploited by attackers, leading to catastrophic consequences.

[0003] Traditional machine learning-based anomaly detection methods treat anomaly detection as a binary or multi-class classification problem through supervised learning. Given sufficient high-quality labeled data, supervised learning methods typically achieve good detection accuracy. However, in the field of smart contract security, obtaining such datasets faces challenges such as scarce labels, high labeling costs, and data imbalance, making it difficult to adapt to the ever-evolving new types of attacks. Unsupervised methods, which do not require pre-labeled data, alleviate the dependence on labeled data to some extent, but also have inherent limitations, such as high false positive rates, difficulty in setting thresholds, and insufficient sensitivity to specific types of anomalies.

[0004] Therefore, there is an urgent need for a new method to detect abnormal transaction information and reduce the false alarm rate of abnormal transaction information in blockchain smart contracts. Summary of the Invention

[0005] Purpose of the invention:

[0006] To address the problems existing in the prior art, this invention proposes a method and system for detecting abnormal transaction information in blockchain smart contracts. By leveraging the information about the data distribution structure contained in unlabeled data, the learning effect on a small amount of labeled data is enhanced.

[0007] Technical solution:

[0008] This invention proposes a method for detecting abnormal transaction information in blockchain smart contracts, comprising:

[0009] The system collects transaction information from a blockchain platform over a period of time, performs data preprocessing on the collected transaction information, and constructs feature engineering that adapts to the dynamic changes of the blockchain, including: inherent and execution features of transactions, account profiles and behavioral pattern features, time series and session features, and network and market state features.

[0010] A semi-supervised model based on an autoencoder is constructed, and a multi-dimensional feature vector selected from feature engineering is input to obtain a reconstructed output. The semi-supervised model is pre-trained in unsupervised mode based on unlabeled data, and the weights obtained after pre-training are retained. Labeled data is obtained, and a training strategy is selected from the preset candidate optimization strategies to calibrate the semi-supervised model to obtain an abnormal transaction detection model.

[0011] Transaction information from the blockchain platform is collected in real time, preprocessed, and then input into the abnormal transaction detection model. The selected training strategy is used to calculate the comprehensive abnormal score of the transaction. The comprehensive abnormal score is compared with a preset decision threshold to determine whether there is any abnormal transaction information.

[0012] Furthermore, the transaction information includes block data, transaction data, transaction receipt data, contract data, account data, and verified source code over a period of time, obtained from the target blockchain platform through the Etherscan API and a self-built Ethereum archive node.

[0013] Furthermore, the preprocessing includes: filling in missing transaction information, standardizing the data format of transaction information of the same type, and cleaning invalid data.

[0014] Furthermore, the selection of the multidimensional feature vector adopts any of the following methods:

[0015] (1) Filtering method: Statistical test to evaluate the correlation between features and labels, use the variance threshold method to remove low variance features, and use correlation coefficient matrix analysis to remove highly redundant features;

[0016] (2) Wrapping method: Iterative feature selection is performed by combining a logistic regression or decision tree;

[0017] (3) Embedding method: Use the semi-supervised model itself to select features and set the coefficients of unimportant features to zero.

[0018] Furthermore, the semi-supervised model includes an encoder and a decoder:

[0019] The encoder includes multiple fully connected hidden layers, with the number of neurons in each layer decreasing progressively; the last layer of the encoder is a latent space, with a dimension much smaller than that of the encoder input layer.

[0020] The decoder includes multiple fully connected hidden layers, with the number of neurons in each layer increasing progressively. The original data is reconstructed from the latent space, and the output layer dimension of the decoder is equal to the input layer dimension of the encoder.

[0021] Furthermore, the candidate optimization strategies include:

[0022] Strategy A: Supervised calibration and adaptive threshold optimization based on reconstruction error;

[0023] Strategy B: End-to-end fine-tuning of an autoencoder or a specific part thereof;

[0024] Strategy C: Supervised classifier training based on latent space representation;

[0025] Strategy D: Iterative self-training based on pseudo-labels;

[0026] Strategy E: Graph-based semi-supervised learning.

[0027] Furthermore, the training strategy is any combination of one or more candidate optimization strategies, and the conditions for selecting a training strategy include: data characteristics and availability, quantity and quality of labeled data, computing resources, and interpretability of the model.

[0028] Furthermore, the calculation method for the comprehensive anomaly score includes:

[0029] If the training strategy is strategy A, the comprehensive anomaly score is the reconstruction error of the current transaction;

[0030] If the training strategy is B or C, the comprehensive anomaly score is the confidence probability output by the additional supervised classifier acting on the latent space.

[0031] If the training strategy is a combined strategy, the comprehensive anomaly score is the weighted sum of the reconstruction error and the confidence probability according to preset weights.

[0032] Furthermore, the preset decision threshold is dynamically adjusted based on the recent overall anomaly level of the network and the risk status of a specific DApp.

[0033] This invention also proposes a blockchain smart contract abnormal transaction information detection system, comprising:

[0034] The feature engineering construction module is used to collect transaction information from the blockchain platform over a period of time, and to preprocess the collected transaction information to build feature engineering that adapts to the dynamic changes of the blockchain, including: inherent and execution features of transactions, account profiles and behavioral pattern features, time series and session features, and network and market state features.

[0035] The model training module is used to construct a semi-supervised model based on an autoencoder. It takes a multi-dimensional feature vector selected from feature engineering as input and obtains a reconstructed output. It performs unsupervised pre-training on the semi-supervised model based on unlabeled data and retains the weights obtained after pre-training. It acquires labeled data, selects a training strategy from preset candidate optimization strategies, calibrates the semi-supervised model, and obtains an abnormal transaction detection model.

[0036] An anomaly detection module is used to collect transaction information from the blockchain platform in real time. After preprocessing, the information is input into the anomaly transaction detection model. The selected training strategy is used to calculate the comprehensive anomaly score of the transaction. The comprehensive anomaly score is compared with a preset decision threshold to determine whether there is any abnormal transaction information.

[0037] Beneficial effects:

[0038] (1) Enhanced detection capability and generalization ability for unknown attacks: This invention, through unsupervised pre-training of an autoencoder on massive amounts of unlabeled transaction data, can deeply learn the inherent patterns and data distribution of normal transaction behavior, constructing an accurate baseline model of normal behavior. This allows the model to be more than limited to known attack signatures; when encountering novel or unknown attacks that significantly deviate from normal patterns, it will produce higher reconstruction errors or appear as outliers in the latent space, thus being effectively identified. Compared with existing supervised learning methods that rely on known attack features, this invention has stronger generalization ability and potential for detecting zero-day attacks.

[0039] (2) Significantly reduced false alarm rate and reduced reliance on manual annotation: The various semi-supervised optimization strategies designed in this invention effectively utilize a small number of labeled normal and abnormal samples. Through these strategies, the model not only learns the general characteristics of normal transactions, but also accurately calibrates the decision boundary between normal and abnormal, thereby significantly improving the sensitivity to the identification of known abnormal types, effectively distinguishing complex but normal transactions from real anomalies, and thus reducing the false alarm rate. Compared with the predicament of high false alarm rate of pure unsupervised methods or the need for a large amount of labeled data in supervised methods in the prior art, this invention significantly reduces the reliance on expensive and scarce manual labeled data while ensuring a high detection rate.

[0040] (3) Achieve quantitative risk assessment: This invention achieves a leap from simple binary classification to refined risk grading by outputting a quantitative anomaly score for each transaction, providing more intuitive decision support and early warning. Attached Figure Description

[0041] Figure 1 This is a schematic diagram of the method flow of the present invention;

[0042] Figure 2 This describes the specific topology of a multilayer fully connected self-encoder.

[0043] Figure 3 This is a schematic diagram of training a supervised classifier based on latent space representation;

[0044] Figure 4 This is a schematic diagram of the iterative self-training process based on pseudo-labels. Detailed Implementation

[0045] The present invention will be further explained below with reference to the accompanying drawings and specific embodiments.

[0046] like Figure 1 The diagram illustrates a method for detecting abnormal transactions in blockchain smart contracts according to the present invention. This method is based on a deep fully connected autoencoder and a latent space XGBoost classifier to detect abnormal transactions in smart contracts on the Ethereum blockchain platform. The specific steps are as follows:

[0047] S1: Data Acquisition

[0048] Using the Etherscan API and a self-built Ethereum archive node, we collected all transaction data, transaction receipt data, block data, and ABIs and verified source code of some contracts from the target blockchain platform over the past 24 months. The data collected in this step forms the basis for subsequent feature engineering (S3) to build comprehensive, multi-dimensional feature vectors, ensuring the richness and discriminative power of the model input. The specific uses of each type of data are as follows:

[0049] Transaction data, transaction receipt data, and block data: These are the core raw data for constructing feature vectors. For example, information such as sender, receiver, transfer value, and gas consumption in "transaction data" is used to construct "inherent and execution features of transactions (Class A)" in S3; event logs in "transaction receipt data" are used to decode and extract key business operations, also serving Class A features; and timestamps, gas limits, etc. in "block data" are used to construct "time series and session features (Class C)" and "network and market state features (Class D)".

[0050] Contract ABI and verified source code: These two types of data are crucial for a deep understanding of transaction behavior. In step S2, the ABI is used to accurately decode transaction input data and event logs, transforming them from raw bytecode into structured information with business meaning. The presence or absence of verified source code is itself an important feature in "Account Profiling and Behavioral Pattern Characteristics (Category B)" (e.g., determining contract credibility).

[0051] The focus is on transactions interacting with smart contracts, specifically transactions where the destination address is the contract address. Initially, approximately 100,000 transaction records and their associated data are collected. The various types of data and their specific granularity collected in this step provide essential raw input for subsequent feature engineering (S3) and are directly related to achieving the purpose of this invention (i.e., accurately detecting abnormal transactions). The specific data types and granularities of the collected data include:

[0052] (1) Block Data: Records block header information, including block number, timestamp, gas limit, gas usage, etc. This data is mainly used to construct network and market state features (Class D) in S3, such as reflecting network congestion by calculating the gas usage rate of blocks; at the same time, the timestamp is the basis for constructing time series and session features (Class C), used to analyze the time interval and frequency of transactions.

[0053] (2) Transaction data: Records transaction hash, sender address, receiver address, transfer value, gas unit price, gas limit, actual gas consumption, transaction input data, etc. This is the core data source for feature engineering in this invention, and is directly used to construct the inherent and execution features of transactions (Class A) and graph / network structure features (Class E).

[0054] (3) Transaction receipt data: Records event logs generated by transactions, cumulative gas usage, etc. Decoding the event logs according to ABI extracts key business operation information within the contract, which is an important supplement to constructing the inherent and execution characteristics of transactions (Type A), such as determining whether a transaction has triggered a high-risk event.

[0055] (4) Contract Data: Records contract address, contract creator address, contract bytecode, source code of verified contracts, and ABI. ABI is an essential tool for accurately decoding transaction input data and event logs in S2 data preprocessing. Information such as the historical behavior of the contract creator and whether the contract is open source is used to construct account profiles and behavioral pattern characteristics (Category B).

[0056] (5) Account data: Records the historical number of transactions and the time of first appearance of the EOA or contract account. This data is directly used to construct account profiles and behavioral pattern characteristics (Category B), such as the account's "on-chain age" and activity level, which are key evidence for judging whether the account's behavioral pattern is abnormal.

[0057] (6) Mempool data (optional, for detecting attacks such as real-time front-running): Records snapshots of transactions to be processed. This data is used to construct detection features for specific real-time attacks (such as front-running and sandwich attacks), enhancing the invention's ability to detect specific attack types.

[0058] S2: Data Preprocessing

[0059] For missing numerical features, appropriate padding strategies are employed, including using statistical values ​​based on transactions from the same block and the same sender, or setting them as special marker values. To ensure data format consistency, all addresses are converted to lowercase, all values ​​are converted to decimal, timestamps are converted to Unix seconds, features with large numerical ranges undergo a log(1+x) transformation, and Boolean operators are converted to 0 or 1. Necessary data cleaning, word segmentation, stop word removal, stemming / lemma reconstruction, etc., are performed to identify and process invalid or contradictory data.

[0060] For transaction input data, the first 4 bytes are extracted as a function selector. The publicly verified ABI of the target contract is used for parameter decoding first. If no ABI is available, a reverse lookup of the function signature is attempted from a public function signature database (e.g., 4byte.directory, etherscan.io / sig). For data that cannot be parsed, metadata such as the length and byte entropy of the transaction input data is recorded. Based on the ABI or the inferred function signature, the encoded parameters are decoded into readable, structured data. For dynamic type parameters, their length and content digest are also recorded. When the transaction input data is empty or does not match any known function selector, it is identified as a call to the fallback or receive function. Transaction input data consisting of contract initialization code and constructor parameters requires special handling.

[0061] For the event logs, the topic and data sections of each event are decoded according to the contract's ABI to extract the event name and parameter values. Events are a direct reflection of contract state changes and important operations, and are crucial for understanding transaction behavior.

[0062] S3: Feature Engineering

[0063] The key to the success of this invention is constructing a comprehensive, discriminative feature engineering mechanism that can adapt to the dynamic changes in the blockchain environment. Features should not only cover the direct attributes of transactions but also include account behavior, contract characteristics, network state, temporal relationships, and deeper semantic information. All transformed and selected features are ultimately combined into a high-dimensional numerical feature vector X∈RD (D is the final feature dimension), which serves as the input to the subsequent autoencoder semi-supervised model. The specific feature engineering design of this invention is as follows:

[0064] A. Inherent and execution characteristics of transactions:

[0065] This includes the amount of native tokens sent in the transaction, the gas unit price, the absolute value of the gas cap, the actual gas consumption, the actual transaction fee, the byte length of the transaction input data, the byte entropy / compression ratio / proportion of non-zero bytes in the input data, the historical frequency of the function selector called in the global or specific contract, the number of function parameters parsed from the transaction input data, the statistical characteristics of numerical parameters, the characteristics of address parameters, the total number of events generated by the transaction, the markers of specific high-risk or critical events, the total number of internal transactions, the total / maximum / average value involved in this part of the transactions, the transaction status, whether it is a transaction created for a contract, and the bytecode size / opcode complexity of the contract creation transaction.

[0066] B. Account profiling and behavioral pattern characteristics:

[0067] This includes historical activity statistics: duration since the account's first on-chain activity, total number of transactions / number of calls to the account, number of successful / failed transactions in the account's history, number of unique counterparty addresses the account has interacted with, and historical behavioral characteristics of the contract creator;

[0068] Fund activity patterns: EOA account balance before and after the transaction, total / average value sent / received by the account in the most recent N transactions, whether the source of funds from the sender can be traced to a known mixing service or high-risk exchange, and whether the account's fund inflows / outflows are highly concentrated in a few counterparties.

[0069] Contract interaction preferences: the types of functions most frequently called by the sender, whether the sender frequently interacts with known high-risk contracts, and whether the receiver's contract verifies the source code.

[0070] C. Timing and conversation characteristics:

[0071] This includes the time interval between the sender's last transaction, the time interval between the receiver's contract and the last time it was invoked by the sender or any other sender, the sender's transaction frequency in different time windows, the suddenness of the sender's transaction behavior, session-level characteristics, and the time difference between consecutive events within the same transaction.

[0072] D. Network and Market Status Characteristics:

[0073] This includes the proportion of the exchange's gas usage in a block relative to the block's gas limit, the average gas price across the entire network when the transaction occurs, and the volatility of the related token prices before and after the transaction.

[0074] E. Graph / Network Structure Characteristics:

[0075] A transaction graph or contract call graph is constructed using nodes as addresses and edges as transactions. The structural features of the transaction graph are also incorporated into the feature engineering of this invention, including the degree centrality of the sender / receiver in the transaction graph, the clustering degree of the sender / receiver's neighbor nodes, the importance score of the sender / receiver in the graph, and the shortest path length from the sender / receiver to a known risk address.

[0076] Use any of the following methods for feature selection:

[0077] (1) Filtering method: Use more extensive statistical tests to evaluate the correlation between features and labels, use the variance threshold method to remove low variance features, and use correlation coefficient matrix analysis to remove highly redundant features.

[0078] (2) Wrap-up method: Combines a simple learning model (such as logistic regression or decision tree) for iterative feature selection. It has a high computational cost, but usually achieves good results.

[0079] (3) Embedding method: Utilize the machine learning model itself to select features, such as L1 regularization, to make the coefficients of unimportant features zero.

[0080] Optionally, for the trained model in subsequent steps, the importance ranking of the features it provides can be analyzed to guide the optimization of feature engineering. For categorical features such as function selectors and event types, one-hot encoding may lead to dimensionality explosion. Using an embedding layer to map them to a low-dimensional dense vector space is a better choice. The embedding layer can be trained inside the autoencoder or as a preprocessing step.

[0081] In this embodiment, a feature vector containing approximately 80 dimensions is extracted for each transaction, covering the aforementioned four categories of features: A, B, C, and D. In addition to basic transaction attributes, the feature vector in this embodiment also includes: the on-chain "age" of the sender and receiver contracts, the total number of historical transactions, the historical success / failure rate, and the number of unique interaction addresses; the sender's transaction frequency, average transaction amount, and gas fee expenditure over the past 1 hour / 24 hours; the frequency of receiver contract calls, average gas consumption, whether it is a newly deployed contract, and whether the creator has a bad record; the length of the transaction input data, the parsed function selector (embedded representation), the number of parameters, and whether there are special value parameters (such as maximum values ​​or zero addresses); the number of events generated by the transaction, whether it includes key events such as Transfer and Approval, and the statistical characteristics of event parameters; the ratio of the transaction to the block gas limit and the deviation from the network average gas price; and the historical correlation between the sender / receiver and known risky addresses (such as TornadoCash routers or addresses of stolen funds).

[0082] All numerical features are ultimately standardized using Z-scores to achieve a mean of 0 and a standard deviation of 1. Categorical features are first converted into numerical IDs, then mapped to low-dimensional dense vectors using an embedding layer, and finally concatenated with other features.

[0083] The innovation of the S3 feature engineering in this invention lies in constructing a comprehensive feature system with multiple dimensions and layers, specifically designed for smart contract interaction scenarios. Compared to existing technologies that typically focus only on the transaction's inherent attributes (such as the A-type features of this invention) or account history (B-type features), this invention systematically integrates inherent transaction features (A), account profiles (B), time series and sessions (C), network state (D), and optional graph structure features (E), thus creating a panoramic and three-dimensional profile of smart contract transaction behavior for the first time. This multi-dimensional feature combination can capture complex attack patterns that are easily overlooked from a single perspective. For example, in a flash loan attack, the value and gas of a single transaction (A-type features) may not appear abnormal, but its high-frequency continuous operations within a very short time window (C-type time series features) and its instantaneous impact on network gas prices (D-type network features) expose its abnormal nature. The feature system of this invention achieves higher sensitivity and stronger discrimination capabilities against complex and novel attack methods through this synergistic effect, thereby significantly improving detection accuracy and reducing false positive rates.

[0084] S4: Construction of a semi-supervised model based on an autoencoder

[0085] like Figure 2 The diagram illustrates the architecture of the autoencoder of this invention. The encoder input layer has a dimension of D, corresponding to the dimension of the high-dimensional transaction feature vector after feature engineering. The encoder consists of multiple fully connected hidden layers, with the number of neurons in each layer typically decreasing progressively to compress the data. The diagram shows the number of neurons and activation function used in each fully connected hidden layer in this embodiment. The bottleneck layer (latent space) is the last layer of the encoder, with a dimension of M (M≪D), representing a compact representation of the original data in a low-dimensional space.

[0086] The decoder is typically symmetrical (or approximately symmetrical) to the encoder structure, consisting of multiple fully connected hidden layers. The number of neurons in each layer increases progressively, reconstructing the original data from the aforementioned latent space. The output layer has dimension D and represents the reconstruction result of the original input feature vector by the autoencoder. Its activation function needs to be selected based on the normalization method of the input data.

[0087] This embodiment employs a deep fully connected autoencoder, DeepAE, with the input layer set to the 80-dimensional feature vector obtained from S3. The loss function is set to mean squared error loss, and the sum of squares of the differences between the original input X and the reconstructed output X^ is calculated. The encoder used specifically includes:

[0088] DenseLayer1:128neurons, LeakyReLUactivation, BatchNormalization.

[0089] DenseLayer2:64neurons, LeakyReLUactivation, BatchNormalization.

[0090] DenseLayer3 (Bottleneck): 32 neurons, LeakyReLUactivation (latent space dimension M=32).

[0091] The decoders used specifically include:

[0092] DenseLayer4:64neurons, LeakyReLUactivation, BatchNormalization.

[0093] DenseLayer5:128neurons, LeakyReLUactivation, BatchNormalization.

[0094] DenseLayer6(Output): 80 neurons, Linearactivation (because the input has been standardized, the reconstruction target is also a standardized value).

[0095] S5: Large-scale unsupervised pre-training based on unlabeled data

[0096] In order for the autoencoder to learn an effective, compact and representative representation of normal blockchain transaction data in a low-dimensional latent space, and to reconstruct the original normal transaction from the latent representation with the smallest possible error, it is necessary to train the model built by S4 and learn the normal transaction pattern.

[0097] The vast majority (90% to 99%) of the data collected from S1 was selected as the unlabeled training set. Ideally, this set should consist primarily of normal transactions, or at least normal transaction patterns should dominate, allowing the autoencoder to learn "what is normal." Further end-to-end training is performed on the selected autoencoder architecture, choosing an appropriate optimizer, learning rate scheduling strategy, batch size, and training epochs.

[0098] Abnormal transactions, due to their patterns differing from learned normal patterns, are expected to lead to higher reconstruction errors, or their latent representations may deviate from the clustering regions of normal samples in the latent space. The weights of the trained encoder and decoder are preserved as the basis for subsequent semi-supervised stages.

[0099] S6: Diversified Semi-Supervised Optimization and Calibration Incorporating Limited Labeled Data

[0100] Publicly available security incident reports were analyzed to obtain labeled data. These reports included information on ReentrancyGuard exploits, various DeFi flash loan attacks, lists of known phishing contract addresses, and RugPull project addresses. Using a community-provided blacklist address database and small-scale expert annotation, approximately 10,000 labeled transactions were initially compiled, including about 2,000 known abnormal transactions and 8,000 transactions considered normal, thus constructing a labeled dataset. It is used for semi-supervised optimization and subsequent evaluation.

[0101]

[0102] Where 0 represents normal, 1 represents abnormal, and M≪N. Utilizing... The pre-trained model obtained from S5 is fine-tuned and the decision boundary is optimized.

[0103] To address the high-dimensional, sparse, and dynamically evolving characteristics of blockchain transaction data, this invention proposes a flexible, composable, and systematic semi-supervised optimization framework. Existing technologies, when applying semi-supervised learning, often employ a single, predetermined method in isolation (such as simple pseudo-labeling or training a classifier only in the latent space). This "one-size-fits-all" approach struggles to adapt to complex and ever-changing on-chain attack patterns, resulting in limited effectiveness. The framework designed in this invention provides multiple optimization strategies (subsequent strategies A through E) and allows them to work collaboratively, maximizing the extraction of information value from a limited amount of labeled data. This significantly improves the model's accuracy in identifying normal and abnormal boundaries and its generalization ability against unknown attacks. The various semi-supervised strategies supported by this invention are as follows:

[0104] Strategy A: Supervised calibration and adaptive threshold optimization based on reconstruction error.

[0105] Will All samples are input into the S5 pre-trained autoencoder, and the reconstruction error of each sample is calculated. The reconstruction error distribution P(e|y=0) of normal samples and the reconstruction error distribution P(e|y=1) of abnormal samples are observed separately. Ideally, these two distributions should be clearly separated.

[0106] use Yes, by evaluating classification performance metrics (such as F1-score, precision, and recall) under different reconstruction error thresholds θ, the optimal global threshold is selected. Here, the threshold θ is a preset value used to determine whether a transaction is abnormal: if the reconstruction error of a transaction... If θ is greater than or equal to θ, the transaction is classified as abnormal; otherwise, it is considered normal. (Regarding reconstruction error...) A simple supervised classifier is trained based on the features. Complex contract calls typically have higher errors than simple transfers. Considering that different types of normal transactions may have different reconstruction error baselines, the threshold for anomaly detection is dynamically adjusted based on the meta-characteristics of the transaction (such as transaction type, contract complexity, etc.) or the statistical characteristics of short-term transaction flows, rather than using a single global threshold. A small amount of labeled data can be used to learn this dynamic adjustment strategy.

[0107] Strategy B: End-to-end fine-tuning of an autoencoder or a specific part thereof.

[0108] Based on the pre-trained autoencoder, using Fine-tuning is performed. Its total loss function is a combination of multiple tasks, specifically expressed as:

[0109]

[0110] The reconstruction loss, similar to that in the unsupervised pre-training phase, is typically the mean squared error (MSE), used to penalize the model for inaccuracies in reconstructing input samples (especially normal samples). This is the classification loss. This loss is derived from the latent space representation in the encoder. This is followed by a small classification head (such as one or more fully connected layers). This classification head directly predicts the label of the sample. The classification loss is usually achieved using the cross-entropy loss function. and Used to measure the difference between predicted and true labels. It is a weighted hyperparameter used to balance the importance of reconstruction and classification tasks.

[0111] By minimizing this joint total loss function, the model, during the fine-tuning phase, not only maintains its ability to reconstruct normal samples, but also learns how to effectively distinguish between normal and abnormal samples in its internal representation (latent space).

[0112] Strategy C: Supervised classifier training based on latent space representation.

[0113] like Figure 3 The diagram shows the flow chart of strategy C, which uses a pre-trained and fixed encoder part. ,Will All samples Mapping to its low-dimensional latent space representation . This is considered a new and superior feature. The specific steps are as follows:

[0114] After passing through S5, an autoencoder model pre-trained on a large amount of unlabeled data is obtained. A small number of labeled transaction samples (containing both normal and abnormal classes, with known labels) are input into the encoder part of the pre-trained autoencoder. The encoder processes each high-dimensional input sample... Convert to its corresponding low-dimensional latent space representation .

[0115] Extracted latent features Compared to its original authentic label Pairing them together creates a new, lower-dimensional training set of latent features. On this latent feature training set, train an independent, high-performance supervised learning classifier to learn from the latent features. To tag The mapping relationship.

[0116] In these latent feature-label pairs In this case, an independent supervised classifier is trained. Due to the low dimensionality and high information density of the latent features, the classifier usually achieves good performance.

[0117] This method decouples feature extraction from classification, making it easy to implement and optimize. The autoencoder focuses on learning a general data representation, while the classifier focuses on accurate discrimination using a small number of labels.

[0118] Strategy D: Iterative self-training based on pseudo-labels.

[0119] like Figure 4 The diagram shows the process flow of strategy D, which uses a pre-trained autoencoder to process a large amount of unlabeled data. Make a prediction to obtain the reconstruction error or classification probability.

[0120] A subset of unlabeled samples with very high confidence levels from the model predictions are selected and assigned pseudo-labels. For example, samples with reconstruction errors far below a certain strict threshold are labeled "pseudo-normal," and samples far above another strict threshold are labeled "pseudo-abnormal"; or samples whose classifier output probabilities are close to 0 or 1. These pseudo-labeled samples are then compared with a small number of real labeled samples. Merge to form an expanded training set. .use Retrain or fine-tune the model. Repeat the above steps, with the model using its own generated pseudo-labels to improve performance in each iteration. Stop iterating when the set stopping criteria are met.

[0121] Optionally, in conjunction with active learning, during the pseudo-label generation stage, the most "uncertain" unlabeled samples in the model are selected for manual labeling to make the most efficient use of the manual labeling budget.

[0122] Strategy E: Graph-based semi-supervised learning.

[0123] If class E features (transaction graph or account interaction graph) are constructed in S2, the labels of a small number of labeled nodes are propagated to unlabeled nodes through the graph structure. For example, a label propagation algorithm or a graph convolutional network (GCN) can be used for node classification, where the input features of the GCN come from node representations extracted by an autoencoder.

[0124] The choice of a combination of semi-supervised strategies depends on the specific characteristics of the data, the quantity and quality of the labeled data, computational resources, and the requirements for model interpretability. The strategies A through E proposed above are not mutually exclusive, nor can only be used one at a time; rather, they constitute a flexible and composable optimization framework. In practical applications, a single strategy can be selected based on the specific situation, or multiple strategies can be stacked or used in series to achieve better detection results.

[0125] Example of combined use: An efficient combination approach is to first use strategy C to train a high-performance supervised classifier on the high-quality latent space features extracted by the pre-trained model; then, use this classifier to predict a large amount of unlabeled data, and use its high-confidence prediction results as the basis for generating pseudo-labels in strategy D, and then perform iterative self-training to form an enhanced closed loop of "strong classifier guiding pseudo-label generation".

[0126] The conditions and limitations for selecting a strategy mainly depend on the following factors:

[0127] (1) Data characteristics and availability: If a transaction graph or account interaction graph (E-type feature) is constructed in S2, then strategy E (graph-based semi-supervised learning) becomes an option. If such structured data is not available, it is not applicable.

[0128] (2) Quantity and quality of labeled data: When labeled data is extremely scarce but of high quality, strategy C, which trains the classifier directly in the latent space, may be the most robust. If the amount of labeled data is slightly larger, consider combining strategy D for iterative self-training to expand the data.

[0129] (3) Computational resources: Strategy D and Strategy B (end-to-end fine-tuning) have relatively high computational costs due to iterative training or backpropagation of large models. Strategy A (threshold optimization based on reconstruction error) and Strategy C have lower computational costs and are faster to deploy.

[0130] (4) Requirements for model interpretability: Strategy A has the simplest and most intuitive logic (the larger the reconstruction error, the more abnormal it is), and has the strongest interpretability. Other strategies (especially strategy B, which involves end-to-end fine-tuning) are more like a "black box".

[0131] The core of the semi-supervised learning model proposed in this invention lies in providing a set of modular and composable optimization strategies. This invention fully supports all the strategies described in A to E above and any reasonable combinations thereof, providing a specially designed, verified, flexible, and effective systematic solution for solving the problem of abnormal transaction detection in blockchain.

[0132] After implementing one or more semi-supervised optimization strategies in S6, this invention yields a fully trained and finely calibrated final abnormal transaction detection model. This model has learned the general patterns of normal transactions from massive amounts of unlabeled data (S5) and accurately delineates the decision boundaries between normal and abnormal behavior using a small amount of high-quality labeled data.

[0133] The final model derived from S6 is the core engine for subsequent real-time or batch anomaly transaction detection (i.e., step S7). In subsequent applications, new blockchain transaction data, after undergoing the same preprocessing and feature engineering, will be input into this model. The model will quickly calculate its anomaly score or directly provide a classification result, thereby achieving real-time monitoring and early warning of on-chain transactions.

[0134] S7: Perform real-time abnormal transaction detection

[0135] Real-time blockchain transaction data is acquired and transformed into standardized feature vectors through data preprocessing and feature engineering processes from S1 to S3. .Will The input is fed into an autoencoder system that has undergone full training from S4 to S6 and semi-supervised optimization. The semi-supervised strategy is specified, and the system calculates the overall anomaly score for the transaction. The calculation method for this comprehensive anomaly score depends specifically on the semi-supervised optimization strategy ultimately adopted in step S6:

[0136] If strategy A (based on reconstruction error) is primarily adopted: This is the reconstruction error of the transaction. Or, it could be the anomaly probability value output by a simple classifier trained on top of the reconstruction error.

[0137] If strategy B or C (based on classifier) ​​is primarily used: It is the confidence probability output by the additional supervised classifier (acting in the latent space or as part of the model) that classifies the transaction as an anomalous category (labeled "1").

[0138] If a combination strategy is adopted: It is a fusion score obtained by weighting the reconstruction error and the classifier probability according to preset weights, so as to more comprehensively measure the degree of anomaly in the transaction.

[0139] abnormal scores Compared with the preset decision threshold The data is compared to determine if any abnormal transactions exist in the real-time blockchain transaction data. Threshold. It is not completely static, but rather fine-tuned periodically or dynamically based on the overall anomaly level of the network recently, the risk status of specific DApps, and even false alarms / missed alarms reported by users.

[0140] In summary, the core innovation of this invention lies in overcoming the limitations of existing technologies by constructing a systematic, multi-stage detection process. First, through the unique multi-dimensional comprehensive feature system in S3 (covering inherent transaction attributes, account profiles, time series, network states, and graph structures), a panoramic profile of transaction behavior is constructed, fundamentally improving the quality and discriminative power of the model input, enabling it to capture complex attack patterns that are difficult to detect from a single perspective. Second, in S5, an autoencoder is used for unsupervised pre-training on massive amounts of unlabeled data, laying a solid foundation for the model to identify unknown attacks.

[0141] Most importantly, in S6, this invention does not simply apply a single semi-supervised algorithm, but proposes a modular and composable semi-supervised optimization framework. This framework allows for the flexible selection or combination of multiple optimization strategies (such as combining latent space-based classifier training with pseudo-label-based iterative self-training) based on actual needs such as data characteristics, the number of labeled samples, and computational resources. This maximizes the value of a small amount of labeled data and achieves accurate calibration of the decision boundary. Finally, through the quantitative risk scoring in S7, an improvement from simple binary classification to refined risk warning is achieved.

Claims

1. A method for detecting abnormal transaction information in blockchain smart contracts, characterized in that, include: The system collects transaction information from a blockchain platform over a period of time, performs data preprocessing on the collected transaction information, and constructs feature engineering that adapts to the dynamic changes of the blockchain, including: inherent and execution features of transactions, account profiles and behavioral pattern features, time series and session features, and network and market state features. A semi-supervised model based on an autoencoder is constructed, and a multi-dimensional feature vector selected from feature engineering is input to obtain a reconstructed output. The semi-supervised model is pre-trained in unsupervised mode based on unlabeled data, and the pre-trained weights are retained. Labeled data is obtained, a training strategy is selected from the preset candidate optimization strategies, and the semi-supervised model is calibrated based on the pre-trained weights to obtain an abnormal transaction detection model. Transaction information from the blockchain platform is collected in real time, preprocessed, and then input into the abnormal transaction detection model. A training strategy is used to calculate the comprehensive abnormal score of the transaction. The comprehensive abnormal score is compared with a preset decision threshold to determine whether there is any abnormal transaction information.

2. The abnormal transaction information detection method according to claim 1, characterized in that, The transaction information includes block data, transaction data, transaction receipt data, contract data, account data, and verified source code over a period of time, obtained from the target blockchain platform through the Etherscan API and a self-built Ethereum archive node.

3. The abnormal transaction information detection method according to claim 2, characterized in that, The preprocessing includes: filling in missing transaction information, standardizing the data format of transaction information of the same type, and cleaning invalid data.

4. The abnormal transaction information detection method according to claim 3, characterized in that, The multidimensional feature vectors are selected using any of the following methods: (1) Filtering method: Statistical test to evaluate the correlation between features and labels, use the variance threshold method to remove low variance features, and use correlation coefficient matrix analysis to remove highly redundant features; (2) Wrapping method: Iterative feature selection is performed by combining a logistic regression or decision tree; (3) Embedding method: Use the semi-supervised model itself to select features and set the coefficients of unimportant features to zero.

5. The abnormal transaction information detection method according to claim 4, characterized in that, The semi-supervised model includes an encoder and a decoder: The encoder includes multiple fully connected hidden layers, with the number of neurons in each layer decreasing progressively; the last layer of the encoder is a latent space, with a dimension much smaller than that of the encoder input layer. The decoder includes multiple fully connected hidden layers, with the number of neurons in each layer increasing progressively. The original data is reconstructed from the latent space, and the output layer dimension of the decoder is equal to the input layer dimension of the encoder.

6. The abnormal transaction information detection method according to claim 5, characterized in that, The candidate optimization strategies include: Strategy A: Supervised calibration and adaptive threshold optimization based on reconstruction error; Strategy B: End-to-end fine-tuning of an autoencoder or a specific part thereof; Strategy C: Supervised classifier training based on latent space representation; Strategy D: Iterative self-training based on pseudo-labels; Strategy E: Graph-based semi-supervised learning.

7. The abnormal transaction information detection method according to claim 6, characterized in that, The training strategy is any combination of one or more candidate optimization strategies. The conditions for selecting a training strategy include: data characteristics and availability, quantity and quality of labeled data, computing resources, and interpretability of the model.

8. The abnormal transaction information detection method according to claim 7, characterized in that, The calculation method for the comprehensive anomaly score includes: If the training strategy is strategy A, the comprehensive anomaly score is the reconstruction error of the current transaction; If the training strategy is B or C, the comprehensive anomaly score is the confidence probability output by the additional supervised classifier acting on the latent space. If the training strategy is a combined strategy, the comprehensive anomaly score is the weighted sum of the reconstruction error and the confidence probability according to preset weights.

9. The abnormal transaction information detection method according to claim 8, characterized in that, The preset decision threshold is dynamically adjusted based on the recent overall anomaly level of the network and the risk status of specific DApps.

10. A blockchain smart contract abnormal transaction information detection system, characterized in that, include: The feature engineering construction module is used to collect transaction information from the blockchain platform over a period of time, and to preprocess the collected transaction information to build feature engineering that adapts to the dynamic changes of the blockchain, including: inherent and execution features of transactions, account profiles and behavioral pattern features, time series and session features, and network and market state features. The model training module is used to construct a semi-supervised model based on an autoencoder. It takes a multi-dimensional feature vector selected from feature engineering as input and obtains a reconstructed output. It performs unsupervised pre-training on the semi-supervised model based on unlabeled data and retains the pre-training weights. It obtains labeled data, selects a training strategy from preset candidate optimization strategies, and calibrates the semi-supervised model based on the pre-training weights to obtain an abnormal transaction detection model. An anomaly detection module is used to collect transaction information from the blockchain platform in real time. After preprocessing, the information is input into the anomaly transaction detection model. The model uses a training strategy to calculate a comprehensive anomaly score for the transaction and compares the comprehensive anomaly score with a preset decision threshold to determine whether there is any abnormal transaction information.